package service.creditmanage.impl;

import hirondelle.date4j.DateTime;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import core.global.Global;
import model.TContract;
import model.company.Companybasic;
import model.company.Companymanage;
import model.personal.Personalbasic;
import model.contract.Loangrant;
import model.contract.Loangrantrecord;
import model.contract.Loaninterest;
import model.contract.Loaninterestrecord;
import model.credit.Lcbank;
import dao.CompanybasicDao;
import dao.CompanymanageDao;
import dao.LcBankDao;
import dao.LoangrantDao;
import dao.LoangrantrecordDao;
import dao.LoaninterestDao;
import dao.LoaninterestrecordDao;
import dao.PersonalbasicDao;
import dao.TContractDao;
import exception.Exceptions;

import service.app.CreatKeyService;
import service.app.InfoService;
import service.creditmanage.CreditManageService;
import util.Time;
import util.Tool;

public class CreditManageServiceImpl implements CreditManageService{
	private TContractDao contractDao;
	private LoangrantDao loangrantDao;
	private LoaninterestDao loaninterestDao;
	private PersonalbasicDao personalbasicDao;
	private CompanybasicDao companybasicDao;
	private LcBankDao lcBankDao;
	private CreatKeyService creatKeyService;
	private InfoService infoService;
	private CompanymanageDao companymanageDao;
	
	private LoangrantrecordDao loangrantrecordDao;
	private LoaninterestrecordDao loaninterestrecordDao;
	
	//待处理借款
	public List getOutList(){
		StringBuffer select=new StringBuffer().append(" ( case  when tc.clienttype=2 then  ( select c.name from companybasic as c where c.id=tc.clientid limit 0,1) ")
				.append(" when tc.clienttype=1 then ( select p.name from personalbasic as p where p.id=tc.clientid limit 0,1)  ")
				.append(" else '0' end ) as customname ,  ")
				.append("tc.Id as id,tc.balance,tc.contractId , tc.startdate ,tc.applymoney ,  ")
				.append(" IFNULL (( select sum(ll.grantmoney) from loangrant as ll where tc.id=ll.contractid and ll.state=2),0) as yifang  ,")
				.append(" IFNULL (( select sum(ll.grantmoney) from loangrant as ll where tc.id=ll.contractid and ll.state=1),0) as daihe ")
				.append("");
		String from="t_contract as tc where tc.contractstate=1 ";
		return loangrantDao.findSqlQuery(select.toString(),from,10);
	}
	
	//待处理的放款条数
	public int getOutUndo(){
		String from="t_contract as tc where tc.contractstate=1 and tc.balance>0";
		return loangrantDao.countSqlQuery(from);
		
	}
	
	//待处理回款条数
	public int getInUndo(){
		//前15天内提醒
		String from="t_contract as tc , loangrant as l where ( l.state=2 or l.state=3  ) and l.balance>0 and l.contractid=tc.id and timestampdiff(day,now(),l.refunddate)<15 and l.userid="+Global.userid();
		return loangrantDao.countSqlQuery(from);
	}
	
	//待处理的利息通知单条数
	public int getInterestUndo(){
		DateTime now = DateTime.now(TimeZone.getDefault());
		DateTime se=now.getStartOfMonth().plusDays(13);//结息前一周
		if(now.gt(se)){
			se = now.plus(0,1,0,0,0,0,0,DateTime.DayOverflow.FirstDay);
		}
		String from="t_contract as tc , loaninterest as li ,loangrant as lg where li.state=1 and li.contractid=tc.id and li.loanid=lg.id and li.balance>0 and li.lastdate<'"+se+"' and li.userid="+Global.userid();
		return loangrantDao.countSqlQuery(from);
	}
	
	//待核实的还款凭证条数
	@Override
	public Object getInUndone() {
		String typestring=null;			
		typestring=" and l.type=1"; //正常为1
		String from="t_contract as tc , loangrantrecord as l where l.state=1 and l.contractid=tc.id "+typestring+" and l.userid="+Global.userid();
		return loangrantDao.countSqlQuery(from);
	}

	//待核实的放款凭证条数
	@Override
	public Object getOutUndone() {
		String from="t_contract as tc , loangrant as l where ( l.state=1 ) and l.contractid=tc.id and l.userid="+Global.userid();
		return loangrantDao.countSqlQuery(from);
	}

	//待核实的利息通知单条数
	@Override
	public Object getInterestUndone() {
		String from="t_contract as tc , loaninterestrecord as li ,loaninterest as loani, loangrant as lg where li.state=1 and li.contractid=tc.id and loani.id=li.loaninterestid and li.loanid=lg.id and li.userid="+Global.userid();
		return loangrantDao.countSqlQuery(from);
	}
	
	//处理完借款列表
	public List<?> getOutDoneList(){
		StringBuffer select=new StringBuffer().append(" ( case  when tc.clienttype=2 then  ( select c.name from companybasic as c where c.id=tc.clientid limit 0,1) ")
				.append(" when tc.clienttype=1 then ( select p.name from personalbasic as p where p.id=tc.clientid limit 0,1)  ")
				.append(" else '0' end ) as customname ,  ")
				.append("l.id,tc.contractId,l.grantnum,l.grantdate,l.grantmoney,l.loangrantnum");
		String from="t_contract as tc , loangrant as l where ( l.state=1 ) and l.contractid=tc.id and l.userid="+Global.userid();
		return loangrantDao.findSqlQuery(select.toString(),from,10);
	}
	
	//待处理利息
	public List<?> getCreditInterestList(){
		DateTime now = DateTime.now(TimeZone.getDefault());
		DateTime se=now.getStartOfMonth().plusDays(20);
		if(now.gt(se)){
			se = now.plus(0,1,0,0,0,0,0,DateTime.DayOverflow.FirstDay);
		}
		
		StringBuffer select=new StringBuffer().append(" ( case  when tc.clienttype=2 then  ( select c.name from companybasic as c where c.id=tc.clientid limit 0,1) ")
				.append(" when tc.clienttype=1 then ( select p.name from personalbasic as p where p.id=tc.clientid limit 0,1)  ")
				.append(" else '0' end ) as customname , ")
				.append("li.id,tc.contractId,lg.grantnum,li.begaindate,li.lastdate,li.principal, ")
				.append("(li.grantmoney+0) as ligrantmoney, li.backmoney, li.balance, ")
				.append("(li.grantmoney-li.backmoney-li.balance) as waitmoney");
		String from="t_contract as tc , loaninterest as li ,loangrant as lg where li.state=1 and li.contractid=tc.id and li.loanid=lg.id and li.lastdate<'"+se+"' and li.userid="+Global.userid();
		return loangrantDao.findSqlQuery(select.toString(),from,10);
		
		/*List<Loangrant> list=loangrantDao.findModel("state=2");
		if(list!=null){
			for(Loangrant loo: list){
				creatInterestList(loo.getId(),loo.getContractid(),loo.getGrantdate());
				loo.setState(3);
				loangrantDao.update(loo);
			}
		}*/		
		
		/*String select="new vo.z.PrintCreditBean(l.id,c.contractId,lg.grantnum,l.begaindate,l.lastdate)";
		String from="TContract as c , Loaninterest as l ,Loangrant as lg where ( l.state=1 ) and l.contractid=c.id and l.loanid=lg.id";
		return loangrantDao.findQuery(select,from,10);*/	
	}
	
	
	//处理完利息
	public List getInterestDoneRecord(){
		StringBuffer select=new StringBuffer().append(" ( case  when tc.clienttype=2 then  ( select c.name from companybasic as c where c.id=tc.clientid limit 0,1) ")
				.append(" when tc.clienttype=1 then ( select p.name from personalbasic as p where p.id=tc.clientid limit 0,1)  ")
				.append(" else '0' end ) as customname , ")
				.append("li.id,tc.contractId,lg.grantnum,li.begaindate,li.lastdate,loani.principal, ")
				.append("(li.grantmoney-0) as ligrantmoney");
		String from="t_contract as tc , loaninterestrecord as li ,loaninterest as loani, loangrant as lg where li.state=1 and li.contractid=tc.id and loani.id=li.loaninterestid and li.loanid=lg.id and li.userid="+Global.userid();
		return loaninterestDao.findSqlQuery(select.toString(),from,10);
	}
	
	
	//待处理还款
	public List<?> getInList(){
		StringBuffer select=new StringBuffer().append(" ( case  when tc.clienttype=2 then  ( select c.name from companybasic as c where c.id=tc.clientid limit 0,1) ")
				.append(" when tc.clienttype=1 then ( select p.name from personalbasic as p where p.id=tc.clientid limit 0,1)  ")
				.append(" else '0' end ) as customname ,  ")
				.append("l.id,tc.contractId,l.grantnum,l.grantdate,l.grantmoney,l.backmoney,l.balance, ")
				.append("(l.grantmoney-l.backmoney-l.balance) as waitmoney");
		String from="t_contract as tc , loangrant as l where ( l.state=2 or l.state=3  ) and l.contractid=tc.id and l.userid="+Global.userid();
		return loangrantDao.findSqlQuery(select.toString(),from,10);
	}

	//处理完还款列表
	@Override
	public List getInDoneRecord(String type) {
		String typestring=null;			
		if("ahead".equals(type)){
			typestring=" and l.type=2"; //提前还款状态为2
		}else if("do".equals(type)){
			typestring=" and l.type=1"; //正常为1
		}else{
			typestring="";
		}
		
		StringBuffer select=new StringBuffer().append(" ( case  when tc.clienttype=2 then  ( select c.name from companybasic as c where c.id=tc.clientid limit 0,1) ")
				.append(" when tc.clienttype=1 then ( select p.name from personalbasic as p where p.id=tc.clientid limit 0,1)  ")
				.append(" else '0' end ) as customname , ")
				.append("l.id,tc.contractId,l.repaydate,l.grantmoney");
		String from="t_contract as tc , loangrantrecord as l where l.state=1 and l.contractid=tc.id "+typestring+" and l.userid="+Global.userid();
		return loangrantDao.findSqlQuery(select.toString(),from,10);
	}
	
	@Override
	public void changePrintDate(Integer id,String type){
		if(type.equals("interest")){
			Loaninterest li=loaninterestDao.findOne("id",id);
			li.setPrintdate(Time.CurrentTimestamp());
			loaninterestDao.save(li);
		}
	}
	
	
	//设置待处理还款 生成凭证
	public String setInChange(int id,BigDecimal money, Timestamp thisdate,String backmethod){
		Loangrant lg=loangrantDao.findOne("Id",id);

		BigDecimal balance=new BigDecimal(lg.getBalance()).setScale(2, BigDecimal.ROUND_HALF_UP);
		if(balance.compareTo(money)==-1){
			return "填写金额过大";
		}
		lg.setBalance(balance.subtract(money).doubleValue());
		loangrantDao.update(lg);
		
		Loangrantrecord lgrecord=new Loangrantrecord();
		lgrecord.setLoanid(id);
		lgrecord.setContractid(lg.getContractid());
		lgrecord.setGrantmoney(money.doubleValue());
		lgrecord.setRepaydate(thisdate);
		if("do".equals(backmethod)){
			lgrecord.setType(1);
		}else if("ahead".equals(backmethod)){
			lgrecord.setType(2);
		}		
		lgrecord.setState(1);
		lgrecord.setUserid(Global.userid());
		loangrantrecordDao.save(lgrecord);		

		return "done";
	}	
	
	//生成放款凭证
	public String setOutChange(int id, BigDecimal money,Timestamp thisdate,Timestamp thatdate){
		TContract tcccc=contractDao.findOne("Id", id);
		BigDecimal balance=new BigDecimal(tcccc.getBalance()).setScale(2, BigDecimal.ROUND_HALF_UP);
		if(balance.compareTo(money)==-1){
			return "填写金额过大";
		}
		tcccc.setBalance(balance.subtract(money).doubleValue());
		contractDao.update(tcccc);		
		
		loangrantDao.findOne("Id",id);
		int count=loangrantDao.countModel("contractid="+id);

		Loangrant lg=new Loangrant();
		lg.setContractid(id);
		lg.setGrantdate(thisdate);
		lg.setRefunddate(thatdate);
		lg.setGrantmoney(money.doubleValue());
		lg.setState(1);
		lg.setGrantnum(count+1);
		lg.setLoangrantnum(creatKeyService.creatKeyFull(41));
		lg.setBackmoney(0.0);
		lg.setBalance(money.doubleValue());
		lg.setUserid(Global.userid());
		loangrantDao.save(lg);
		return "done";
	}
	
	//生成利息凭证
	public String setInterestChange(int id, BigDecimal money, Timestamp thisdate,BigDecimal moneyfuli){
		Loaninterest li=loaninterestDao.findOne("id",id);
		
		BigDecimal balance=new BigDecimal(li.getBalance()).setScale(2, BigDecimal.ROUND_HALF_UP);
		if(balance.compareTo(money)==-1){
			return "填写金额过大";
		}
		li.setCompound(moneyfuli.doubleValue());
		li.setBalance(balance.subtract(money).doubleValue());
		loaninterestDao.update(li);
		
		Loaninterestrecord lirecord=new Loaninterestrecord();
		lirecord.setLoaninterestid(li.getId());
		lirecord.setBegaindate(li.getBegaindate());
		lirecord.setLastdate(li.getLastdate());
		lirecord.setPrintdate(thisdate);
		lirecord.setGrantmoney(money.doubleValue());
		lirecord.setState(1);
		lirecord.setLoanid(li.getLoanid());
		lirecord.setContractid(li.getContractid());
		lirecord.setUserid(Global.userid());
		loaninterestrecordDao.save(lirecord);
		return "done";
	}
	
	
	@Override
	//sure or cancel
	public void changeState(Integer id,String type,String secondtype) {		
		if(type.equals("interest")){
			Loaninterestrecord lirecord=loaninterestrecordDao.findOne("id",id);
			Loaninterest li=loaninterestDao.findOne("id",lirecord.getLoaninterestid());
			lirecord.setConfirmdate(Time.CurrentTimestamp());
			
			if("sure".equals(secondtype)){
				lirecord.setState(0);
				li.setBackmoney(lirecord.getGrantmoney());
			}else if("cancel".equals(secondtype)){
				lirecord.setState(9);
				//还原余额
				
				BigDecimal money=new BigDecimal(lirecord.getGrantmoney()).setScale(2, BigDecimal.ROUND_HALF_UP);
				System.out.println(money);
				BigDecimal balance=new BigDecimal(li.getBalance()).setScale(2, BigDecimal.ROUND_HALF_UP);
				li.setBalance(balance.add(money).doubleValue());
				System.out.println(balance);
				
			}
			loaninterestDao.update(li);
			loaninterestrecordDao.update(lirecord);
		}else if(type.equals("out")){ //放款
			Loangrant lg=loangrantDao.findOne("id",id);			

			if("sure".equals(secondtype)){
				lg.setState(2);
				//创建利息通知单
				creatInterestList(lg.getId());
			}else if("cancel".equals(secondtype)){
				lg.setState(9);
				//还原余额
				TContract tcccc=contractDao.findOne("Id", lg.getContractid());
				BigDecimal money=new BigDecimal(lg.getGrantmoney()).setScale(2, BigDecimal.ROUND_HALF_UP);
				BigDecimal balance=new BigDecimal(tcccc.getBalance()).setScale(2, BigDecimal.ROUND_HALF_UP);
				tcccc.setBalance(balance.add(money).doubleValue());
				contractDao.update(tcccc);
			}			
			loangrantDao.update(lg);
		}else if(type.equals("in")){
			Loangrantrecord lgrecord=loangrantrecordDao.findOne("id",id);
			Loangrant l=loangrantDao.findOne("id",lgrecord.getLoanid());
			if("sure".equals(secondtype)){
				lgrecord.setState(0); 
				l.setBackmoney(lgrecord.getGrantmoney());
				if(lgrecord.getType()==2){//提前还款，删除多余利息通知单
					delPastInterest(lgrecord.getId());
				}				
			}else if("cancel".equals(secondtype)){
				l.setBalance(l.getBalance()+lgrecord.getGrantmoney());
				lgrecord.setState(9); //取消
			}
			loangrantrecordDao.update(lgrecord);
			loangrantDao.update(l);
		}
	}
	
	///////////////////////////////////////////////////	
	public Map<String, Object> getContract(int id,String type) throws Exceptions{
		Map<String, Object> c=new HashMap<String, Object>();
		TContract tc=new TContract();
		if(type.equals("interestcreate")){			
			Loaninterest newli=loaninterestDao.findOne("id",id);
			
			if(newli!=null){
				//Loangrant lo=loangrantDao.findOne("Id",newli.getLoanid());				
				c.put("totalmoney",newli.getPrincipal());
				
				tc=contractDao.findOne("id",newli.getContractid());
				
				DateTime begindate = new DateTime(Time.Timestamp2TimeString(newli.getBegaindate()));
				DateTime enddate = new DateTime(Time.Timestamp2TimeString(newli.getLastdate()));
				
				DateTime tcenddate = new DateTime(Time.Timestamp2TimeString(tc.getEnddate()));
				int twoDaysLenght=begindate.numDaysFrom(enddate);
				
				//还息日期：默认为计息结束日期的第二天（贷款到期日在计息周期内时，还息日期默认为贷款到期日；贷款到期日>计息结束日时，还息日默认为21日）；
				if(enddate.lt(tcenddate)){
					twoDaysLenght+=1;
					c.put("morenhuanxiri",enddate.plusDays(1).format("YYYY-MM-DD"));
				}else{
					c.put("morenhuanxiri",enddate.format("YYYY-MM-DD"));
				}
				
				BigDecimal jishu=new BigDecimal(newli.getPrincipal()*twoDaysLenght).setScale(2, BigDecimal.ROUND_HALF_UP);
				/*BigDecimal lilv=new BigDecimal(tc.getPerformrates()).setScale(5, BigDecimal.ROUND_HALF_UP);
				BigDecimal m360=new BigDecimal(36000);
				BigDecimal lixi=jishu.multiply(lilv).divide(m360,5,BigDecimal.ROUND_HALF_UP).setScale(5, BigDecimal.ROUND_HALF_UP);
				*/
				c.put("jishu",jishu.doubleValue());
				c.put("lixi",newli.getGrantmoney());
				c.put("interestbegindate",begindate.format("YYYY年MM月DD日"));
				c.put("interestenddate",enddate.format("YYYY年MM月DD日"));
		
				//复利计算
				c.put("fuli",0);
				
				//利息合计 =利息+复利
				c.put("lixihe",0);
				
				//实收利息
				//c.put("shishoulixi",0);
				
				c.put("startdate",tc.getStartdate());
				c.put("enddate",tc.getEnddate());
				
				//公司银行账户
				c.put("dcard", infoService.getInfo("interestaccount"));
				c.put("dbank", infoService.getInfo("interestbank"));	
			}else{
				throw new Exceptions("没有找到利息记录!");
			}
		}else if(type.equals("interest")){
			Loaninterestrecord lirecord=loaninterestrecordDao.findOne("id",id);
			Loaninterest li=loaninterestDao.findOne("id",lirecord.getLoaninterestid());
			if(li!=null&&lirecord!=null){
				Loangrant lo=loangrantDao.findOne("Id",li.getLoanid());
				c.put("totalmoney", li.getPrincipal());
				
				tc=contractDao.findOne("id",lo.getContractid());
				
				DateTime begindate = new DateTime(Time.Timestamp2TimeString(lirecord.getBegaindate()));
				DateTime enddate = new DateTime(Time.Timestamp2TimeString(lirecord.getLastdate()));
				
				DateTime tcenddate = new DateTime(Time.Timestamp2TimeString(tc.getEnddate()));
				int twoDaysLenght=begindate.numDaysFrom(enddate);
				if(enddate.lt(tcenddate)){
					twoDaysLenght+=1;
				}
				
				BigDecimal jishu=new BigDecimal(li.getPrincipal()*twoDaysLenght).setScale(2, BigDecimal.ROUND_HALF_UP);
				c.put("jishu",jishu.doubleValue());
				c.put("lixi",lirecord.getGrantmoney());
				c.put("interestbegindate",begindate.format("YYYY年MM月DD日"));
				c.put("interestenddate",enddate.format("YYYY年MM月DD日"));
				
				c.put("pdate",lirecord.getPrintdate());
				
				//复利计算
				BigDecimal fuli=new BigDecimal(li.getCompound());
				c.put("fuli",fuli.doubleValue());
				
				//利息合计 =利息+复利
				c.put("lixihe",Tool.translateMoney(new BigDecimal(lirecord.getGrantmoney()).add(fuli).doubleValue()));
				
				//实收利息
				//c.put("shishoulixi",Tool.translateMoney(li.getBackmoney()));
				
				c.put("startdate",tc.getStartdate());
				c.put("enddate",tc.getEnddate());
				
				//公司银行账户
				c.put("dcard", infoService.getInfo("interestaccount"));
				c.put("dbank", infoService.getInfo("interestbank"));	
				
			}else{
				throw new Exceptions("没有找到利息记录!");
			}
		}else if(type.equals("out")){
			Loangrant lo=loangrantDao.findOne("Id",id);
			tc=contractDao.findOne("id",lo.getContractid());
			//c.put("htnumber", creatKeyService.creatKeyFull(41));	
			c.put("htnumber",lo.getLoangrantnum());	
			c.put("totalmoney",lo.getGrantmoney());
			c.put("totalmoneyarray", double2StringArray(lo.getGrantmoney()));
			c.put("totalmoneychinese", Tool.translateMoney(lo.getGrantmoney()));

			c.put("startdate",lo.getGrantdate());
			c.put("enddate",lo.getRefunddate());
			
			//公司银行账户
			c.put("dcard", infoService.getInfo("principalaccount"));
			c.put("dbank", infoService.getInfo("principalbank"));	
			
			if(lo.getCustombankid()!=null){
				Lcbank lc=lcBankDao.findOne("id",lo.getCustombankid());
				if(lc!=null){
					c.put("cbankname",lc.getBankname());
					c.put("cbankaccount",lc.getSaveaccount());
				}
			}
		}else if(type.equals("outcreate")){
			tc=contractDao.findOne("id",id);
			//c.put("htnumber", creatKeyService.creatKeyFull(41));		
			
			c.put("totalmoney", tc.getBalance());
			c.put("totalmoneyarray", double2StringArray(tc.getBalance()));
			c.put("totalmoneychinese", Tool.translateMoney(tc.getBalance()));
			
			c.put("startdate", tc.getStartdate());	
			c.put("enddate", tc.getEnddate());

			
			//公司银行账户
			c.put("dcard", infoService.getInfo("principalaccount"));
			c.put("dbank", infoService.getInfo("principalbank"));	
		}else if(type.equals("increate")){
			Loangrant lo=loangrantDao.findOne("Id",id);
			tc=contractDao.findOne("id",lo.getContractid());
			c.put("totalmoneyarray", double2StringArray(lo.getBalance()));
			c.put("totalmoney", lo.getBalance());
			c.put("totalmoneychinese", Tool.translateMoney(lo.getBalance()));
			c.put("balance", lo.getBalance());
			
			c.put("startdate",lo.getGrantdate());
			c.put("enddate",lo.getRefunddate());
			//公司银行账户
			c.put("dcard", infoService.getInfo("principalaccount"));
			c.put("dbank", infoService.getInfo("principalbank"));	
		}else if(type.equals("in")){
			Loangrantrecord lgrecord=loangrantrecordDao.findByOne("id="+id);
			Loangrant lo=loangrantDao.findOne("Id",lgrecord.getLoanid());

			c.put("totalmoneyarray", double2StringArray(lgrecord.getGrantmoney()));
			c.put("totalmoney", lgrecord.getGrantmoney());
			c.put("totalmoneychinese", Tool.translateMoney(lgrecord.getGrantmoney()));
				
			c.put("shishou", lgrecord.getGrantmoney());
			c.put("repaydate", lgrecord.getRepaydate());
					
			tc=contractDao.findOne("id",lo.getContractid());	
			
			c.put("balance", lo.getBalance());			
			c.put("yingshou",lo.getGrantmoney());
			
			c.put("startdate",lo.getGrantdate());
			c.put("enddate",lo.getRefunddate());
			//公司银行账户
			c.put("dcard", infoService.getInfo("principalaccount"));
			c.put("dbank", infoService.getInfo("principalbank"));
		}else{

		}
	
		if(tc==null){
			throw new Exceptions("没有找到合同!");
		}
		
		//c.put("totalmoney",tc.getApplymoney());
		c.put("rate",tc.getPerformrates());
		c.put("use",tc.getLoanpurpose());
		c.put("contractname",tc.getContractId());
		
		c.put("date",Time.CurrentTimestamp());
		
		c.put("dname",infoService.getInfo("companyname"));

		
		if(tc.getClienttype().equals("1")){ //个人
			Personalbasic pbasic=personalbasicDao.findOne("id",tc.getClientid());
			if(pbasic!=null){
				c.put("name", pbasic.getName());
			}else{
				throw new Exceptions("没有找到客户信息!");
			}
			
			//查找很行账户信息
			Personalbasic pb=personalbasicDao.findOne("id", tc.getClientid());
			if(pb!=null && (pb.getDraweebank()!=null && pb.getDraweebankid()!=null)&&(!pb.getDraweebank().isEmpty()&& !pb.getDraweebankid().isEmpty())){
				c.put("cbankname",pb.getDraweebank());
				c.put("cbankaccount",pb.getDraweebankid());
			}else{
				Lcbank lc=lcBankDao.findByOne("cid="+tc.getClientid()+" and type=1 ");
				if(lc!=null){
					c.put("cbankname",lc.getBankname());
					c.put("cbankaccount",lc.getSaveaccount());
				}
			}
		}else if(tc.getClienttype().equals("2")){ //公司
			Companybasic cbasic=companybasicDao.findOne("id",tc.getClientid());
			if(cbasic!=null){
				c.put("name", cbasic.getName());
			}else{
				throw new Exceptions("没有找到客户信息!");
			}
			
			//查找很行账户信息
			Companymanage cm=companymanageDao.findOne("cid", tc.getClientid());
			if(cm!=null && ( cm.getDraweebank()!=null && cm.getDraweebankid()!=null) && (!cm.getDraweebank().isEmpty()&& !cm.getDraweebankid().isEmpty())){
				c.put("cbankname",cm.getDraweebank());
				c.put("cbankaccount",cm.getDraweebankid());
			}else{
				Lcbank lc=lcBankDao.findByOne("cid="+tc.getClientid()+" and type=2 ");
				if(lc!=null){
					c.put("cbankname",lc.getBankname());
					c.put("cbankaccount",lc.getSaveaccount());
				}
			}
		}else{}
		
		return c;
	}
	
	private String[] double2StringArray(Double idd){
		BigDecimal abc=new BigDecimal(idd).setScale(2, BigDecimal.ROUND_HALF_UP).movePointRight(2);
		String str=String.valueOf(abc);
		int alength=9-str.length();
		String [] ss=new String[10];
		for(int i=0;i<10;i++){
			if(i>alength){
				ss[i]=String.valueOf(str.charAt(i-alength-1));
			}else{
				ss[i]="";
			}
		}		
		if(alength>=0){
			ss[alength]="￥";
		}
		return ss; 
	}
	
	
	//---借款人账户--------------------------------
	@Override
	public List getCustomBankList(int id,String type) throws Exceptions{
		int loangrantid=id;
		if("interest".equals(type)){
			Loaninterest newli=loaninterestDao.findOne("id",id);
			loangrantid=newli.getLoanid();
		}
		Loangrant lo=loangrantDao.findOne("Id",loangrantid);
		if(lo!=null){
			TContract ctc=contractDao.findOne("id",lo.getContractid());
			if(ctc!=null){
				return lcBankDao.findModel("cid="+ctc.getClientid()+" and type="+ctc.getClienttype());
			}else{
				throw new Exceptions("没有找到客户银行账号!");
			}
			
		}else{
			throw new Exceptions("没有找到客户银行账号!");
		}
	}

	//---利息--------------------------------
	/*	
	//~~利息开始时间
	private DateTime interestBeginDate(Timestamp ttt){
		DateTime begindate = new DateTime(Time.Timestamp2TimeString(ttt));
		
		Loaninterest l=loaninterestDao.findOne("contractid", tc.getId());
		if(l==null){
			return begindate;
		}else{
			DateTime dt = new DateTime(Time.Timestamp2TimeString(l.getLastdate()));
			return dt.plusDays(1);
		}
	}
	
	//~~利息结束时间
	private DateTime interestEndDate(Timestamp ttt){
		//ht enddate
		DateTime enddate = new DateTime(Time.Timestamp2TimeString(ttt));
		//currenttime
		DateTime current = new DateTime(Time.Timestamp2TimeString(Time.CurrentTimestamp()));
		//current20
		DateTime current20 = current.getStartOfMonth().plusDays(19);
		
		return current20.lt(enddate)?current20:enddate;
	}*/
	
	//提前还款，把日期超过还款日的利信通知单删掉。
	private void delPastInterest(int loangrantrecordid){
		Loangrantrecord lgrecord=loangrantrecordDao.findOne("id",loangrantrecordid);
		Timestamp enddate=lgrecord.getRepaydate();
		int loanid=lgrecord.getLoanid();
		BigDecimal thismoney=new BigDecimal(lgrecord.getGrantmoney()).setScale(2, BigDecimal.ROUND_HALF_UP);
		
		Loangrant lg=loangrantDao.findOne("id",loanid);
		List<Loaninterest> list=loaninterestDao.findModel("loanid="+loanid+" and begaindate>'"+enddate+"'");
		Loaninterest lii=loaninterestDao.findByOne("loanid="+loanid+" and ( begaindate <= '"+enddate+"' and '"+enddate+"' <= lastdate )");
		//当确定的还款等于总的放款金额时进行删除，小于则修改
		if(lgrecord.getGrantmoney()>=lg.getGrantmoney()){
			if(list!=null){
				for(Loaninterest l: list){
					loaninterestDao.delete(l);
				}			
			}			
			if(lii!=null){
				lii.setLastdate(enddate);
				loaninterestDao.update(lii);
			}
		}else{
			TContract ctc=contractDao.findOne("id",lg.getContractid());
			Timestamp endtime=ctc.getEnddate();
			BigDecimal lilv=new BigDecimal(ctc.getPerformrates()).setScale(5, BigDecimal.ROUND_HALF_UP);
			if(list!=null){
				for(Loaninterest l: list){
					BigDecimal lixi=sumInterest(thismoney,lilv,l.getBegaindate(),l.getLastdate(),endtime);
					BigDecimal thislixi=new BigDecimal(l.getGrantmoney()).setScale(5, BigDecimal.ROUND_HALF_UP);
					BigDecimal stillLixi=thislixi.subtract(lixi);
					l.setGrantmoney(stillLixi.doubleValue());
					l.setBalance(stillLixi.doubleValue());
					loaninterestDao.update(l);
				}
			}			
			if(lii!=null){
/*				BigDecimal lixi=sumInterest(thismoney,lilv,enddate,lii.getLastdate());
				BigDecimal thislixi=new BigDecimal(lii.getGrantmoney()).setScale(5, BigDecimal.ROUND_HALF_UP);
				BigDecimal stillLixi=thislixi.subtract(lixi);
				lii.setGrantmoney(stillLixi.doubleValue());
				lii.setBalance(stillLixi.doubleValue());
				loaninterestDao.update(lii);	*/
				
				//新加一条待处理利息
				Loaninterest newli=new Loaninterest();
				BigDecimal sheyubenjin=new BigDecimal(lii.getPrincipal()).setScale(2, BigDecimal.ROUND_HALF_UP);
				newli.setLoanid(lii.getLoanid());
				newli.setContractid(lii.getContractid());
				newli.setPrincipal(sheyubenjin.subtract(thismoney).doubleValue());				
				DateTime begaindate = new DateTime(Time.Timestamp2TimeString(enddate)).plusDays(1);
				newli.setBegaindate(Time.Timestring2Timestamp(begaindate.toString()));
				newli.setLastdate(lii.getLastdate());
								
				BigDecimal newlixi=sumInterest(sheyubenjin.subtract(thismoney),lilv,newli.getBegaindate(),newli.getLastdate(),endtime);
				newli.setGrantmoney(newlixi.doubleValue());
				newli.setBalance(newlixi.doubleValue());
				
				newli.setState(1);
				newli.setBackmoney(0.0);
				newli.setUserid(Global.userid());
				loaninterestDao.save(newli);
				
				//处理原来的一条记录
				lii.setLastdate(enddate);				
				BigDecimal thisprincipal=new BigDecimal(lii.getPrincipal()).setScale(2, BigDecimal.ROUND_HALF_UP);
				BigDecimal lixi=sumInterest(thisprincipal,lilv,lii.getBegaindate(),lii.getLastdate(),endtime);
				lii.setGrantmoney(lixi.doubleValue());
				lii.setBalance(lixi.doubleValue());
				loaninterestDao.update(lii);

				//System.out.println("new money a"+lii.getId()+"~"+lixi+"~"+thislixi+"~"+stillLixi);
			}
		}	

	}
	
	//~~~创建利息各月的记录
	/*
	 * loanid loangrant号
	 * contractid 合同号
	 * begin 放款开始日期
	 */
	private void creatInterestList(int loanid){
		Loangrant lo=loangrantDao.findOne("Id",loanid);
		TContract ctc=contractDao.findOne("id",lo.getContractid());
		Timestamp endtime=ctc.getEnddate();
		//计算利息 1/2
		//利率
		BigDecimal lilv=new BigDecimal(ctc.getPerformrates()).setScale(5, BigDecimal.ROUND_HALF_UP);
		BigDecimal fafangjie=new BigDecimal(lo.getGrantmoney());
		List<Timestamp> list=Time.dateBetweenTwoDaysList(lo.getGrantdate(),lo.getRefunddate(),20);
		
		int contractid=lo.getContractid();
		Double money=lo.getGrantmoney();
		int size=list.size()-1;
		for(int i=0;i<size;i++){
			Loaninterest lii=new Loaninterest();
			lii.setLoanid(loanid);
			lii.setContractid(contractid);
			lii.setPrincipal(money);
			if(i==0){
				lii.setBegaindate(list.get(i));
			}else{
				DateTime dd = new DateTime(Time.Timestamp2TimeString(list.get(i)));
				dd=dd.plusDays(1);
				lii.setBegaindate(Time.Timestring2Timestamp(dd.toString()));
			}
			lii.setLastdate(list.get(i+1));
			lii.setState(1);
			
			//利息
			BigDecimal lixi=sumInterest(fafangjie,lilv,lii.getBegaindate(), lii.getLastdate(),endtime);
			lii.setGrantmoney(lixi.doubleValue());
			lii.setBackmoney(0.0);
			lii.setBalance(lixi.doubleValue());
			lii.setUserid(Global.userid());
			loaninterestDao.save(lii);
		}		
	}
	
	//计算利息
	private BigDecimal sumInterest(BigDecimal benjin,BigDecimal lilv,Timestamp begindate,Timestamp enddate,Timestamp huankuanri){
		//日期长度
		int twoDaysLenght=Time.datediff(begindate,enddate);
		
		DateTime jieshuriqi=new DateTime(Time.Timestamp2TimeString(enddate));
		DateTime tcenddate = new DateTime(Time.Timestamp2TimeString(huankuanri));
		if(jieshuriqi.lt(tcenddate)){
			twoDaysLenght+=1;
		}
		
		System.out.println("twoDaysLenght"+twoDaysLenght);	
		//积数
		BigDecimal jishu=benjin.multiply(new BigDecimal(Double.valueOf(twoDaysLenght))).setScale(2, BigDecimal.ROUND_HALF_UP);
		//360*100
		BigDecimal m360=new BigDecimal(36000);	
		return jishu.multiply(lilv).divide(m360,5,BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
	}
	
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	public TContractDao getContractDao() {
		return contractDao;
	}
	public void setContractDao(TContractDao contractDao) {
		this.contractDao = contractDao;
	}
	public PersonalbasicDao getPersonalbasicDao() {
		return personalbasicDao;
	}
	public void setPersonalbasicDao(PersonalbasicDao personalbasicDao) {
		this.personalbasicDao = personalbasicDao;
	}
	public CompanybasicDao getCompanybasicDao() {
		return companybasicDao;
	}
	public void setCompanybasicDao(CompanybasicDao companybasicDao) {
		this.companybasicDao = companybasicDao;
	}
	public LoangrantDao getLoangrantDao() {
		return loangrantDao;
	}
	public void setLoangrantDao(LoangrantDao loangrantDao) {
		this.loangrantDao = loangrantDao;
	}

	public LoaninterestDao getLoaninterestDao() {
		return loaninterestDao;
	}

	public void setLoaninterestDao(LoaninterestDao loaninterestDao) {
		this.loaninterestDao = loaninterestDao;
	}

	public CreatKeyService getCreatKeyService() {
		return creatKeyService;
	}

	public void setCreatKeyService(CreatKeyService creatKeyService) {
		this.creatKeyService = creatKeyService;
	}

	public InfoService getInfoService() {
		return infoService;
	}

	public void setInfoService(InfoService infoService) {
		this.infoService = infoService;
	}

	public LcBankDao getLcBankDao() {
		return lcBankDao;
	}

	public void setLcBankDao(LcBankDao lcBankDao) {
		this.lcBankDao = lcBankDao;
	}

	public LoaninterestrecordDao getLoaninterestrecordDao() {
		return loaninterestrecordDao;
	}

	public void setLoaninterestrecordDao(LoaninterestrecordDao loaninterestrecordDao) {
		this.loaninterestrecordDao = loaninterestrecordDao;
	}

	public LoangrantrecordDao getLoangrantrecordDao() {
		return loangrantrecordDao;
	}

	public void setLoangrantrecordDao(LoangrantrecordDao loangrantrecordDao) {
		this.loangrantrecordDao = loangrantrecordDao;
	}

	public CompanymanageDao getCompanymanageDao() {
		return companymanageDao;
	}

	public void setCompanymanageDao(CompanymanageDao companymanageDao) {
		this.companymanageDao = companymanageDao;
	}
}
